<?php
/**
 * Created by PhpStorm.
 * @author hebidu <email:346551990@qq.com>
 * @modify 2017-07-14 10:00:04
 */

namespace app\domain;

use app\domain\dto\UserDeviceUpdateDTO;
use app\src\base\helper\ResultHelper;
use app\src\base\helper\ValidateHelper;
use app\src\ipAddress\IP;
use app\src\sunsun\common\action\UserDeviceAction;
use app\src\sunsun\common\helper\DeviceTypeHelper;
use app\src\sunsun\filterVat\logic\FilterVatDeviceLogic;
use sunsun\server\consts\DeviceType;


/**
 * Class SunsunUserDeviceDomain
 * 用户设备
 * @package app\domain
 */
class SunsunUserDeviceDomain extends BaseDomain
{
    public function __construct($algInstance, $data)
    {
        parent::__construct($algInstance, $data);
    }

    public function update()
    {
        $dto = new UserDeviceUpdateDTO($this->getOriginData());
        $action = new UserDeviceAction();
        $map = ['uid' => $dto->getUid()];
        $entity = ['lang' => $dto->getLang(), 'timezone' => $dto->getTimezone()];
        $result = $action->save($map, $entity);
        $this->returnResult($result);
    }


    /**
     * water_pump 额外信息
     */
    public function updateWaterPumpExtra()
    {
        $id = $this->_post('id', 0);
        $push_cfg = $this->_post('push_cfg', '');
        $fcd = $this->_post('fcd', '');
        $state = $this->_post('state', '');
        $action = new UserDeviceAction();
        $id = intval($id);
        if ($id <= 0) {
            $this->apiReturnErr('设备id无效(-1)');
        }
        $result = $action->getInfo($id);
        $entity = $result['info'];
        if (empty($entity)) {
            $this->apiReturnErr('设备id无效(-2)');
        }
//        $did = $entity['did'];
        $extra = json_decode($entity['extra'], JSON_OBJECT_AS_ARRAY);
        if (!is_array($extra)) {
            $extra = [];
        }
        if (ValidateHelper::isZeroOrOne($push_cfg)) {
            $extra['push_cfg'] = $push_cfg;
        }
        if (strlen($fcd) > 0) {
            $extra['fcd'] = intval($fcd);
        }
        $data = [];
        $data['extra'] = json_encode($extra);
        $result = (new UserDeviceAction())->userDeviceChange($id, $data);
        if ($result['status']) {
            $this->apiReturnSuc(lang('success'));
        } else {
            $this->apiReturnErr(lang("fail"));
        }
    }


    /**
     * adt 额外信息
     */
    public function updateAdtExtra()
    {
        $id = $this->_post('id', 0);
        $push = $this->_post('push', '');
        $action = new UserDeviceAction();
        $id = intval($id);
        if ($id <= 0) {
            $this->apiReturnErr('设备id无效(-1)');
        }
        $result = $action->getInfo($id);
        $entity = $result['info'];
        if (empty($entity)) {
            $this->apiReturnErr('设备id无效(-2)');
        }

        $extra = json_decode($entity['extra'], JSON_OBJECT_AS_ARRAY);

        if (ValidateHelper::isZeroOrOne($push)) {
            $extra['push'] = $push;
        }
        $data = [];
        $data['extra'] = json_encode($extra);
        $result = (new UserDeviceAction())->userDeviceChange($id, $data);
        $this->exitWhenError($result, true);
    }

    /**
     * 加热棒额外信息
     */
    public function updateHeatingExtra()
    {
        $id = $this->_post('id', 0);
        $abnormal = $this->_post('abnormal', '');
        $action = new UserDeviceAction();
        $id = intval($id);
        if ($id <= 0) {
            $this->apiReturnErr('设备id无效(-1)');
        }
        $result = $action->getInfo($id);
        $entity = $result['info'];
        if (empty($entity)) {
            $this->apiReturnErr('设备id无效(-2)');
        }

        $extra = json_decode($entity['extra'], JSON_OBJECT_AS_ARRAY);

        if (ValidateHelper::isZeroOrOne($abnormal)) {
            $extra['abnormal'] = $abnormal;
        }
        $data = [];
        $data['extra'] = json_encode($extra);
        $result = (new UserDeviceAction())->userDeviceChange($id, $data);
        $this->exitWhenError($result, true);
    }

    /**
     * 过滤桶额外信息
     */
    public function updateFilterVatExtra()
    {
        $id = $this->_post('id', 0);
        $notify_email = $this->_post('notify_email', '');
        $fcd = $this->_post('fcd', '');
        $oa_name = $this->_post('oa_name', '');
        $ob_name = $this->_post('ob_name', '');
        $action = new UserDeviceAction();
        $id = intval($id);
        if ($id <= 0) {
            $this->apiReturnErr('设备id无效(-1)');
        }
        $result = $action->getInfo($id);
        $entity = $result['info'];
        if (empty($entity)) {
            $this->apiReturnErr('设备id无效(-2)');
        }
        $extra = json_decode($entity['extra'], JSON_OBJECT_AS_ARRAY);

        if (ValidateHelper::isZeroOrOne($notify_email)) {
            $extra['notify_email'] = $notify_email;
        }
        if (strlen($oa_name) > 0) {
            $extra['oa_name'] = $oa_name;
        }
        if (strlen($ob_name) > 0) {
            $extra['ob_name'] = $ob_name;
        }
        $data = [];
        $data['extra'] = json_encode($extra);
        $result = (new UserDeviceAction())->userDeviceChange($id, $data);
        $this->exitWhenError($result, true);
    }

    /**
     * aq806额外信息
     */
    public function updateAq806Extra()
    {
        $id = $this->_post('id', 0);
        $ph_on = $this->_post('ph_on', '');
        $ph_l = $this->_post('ph_l', '');
        $ph_h = $this->_post('ph_h', '');
        $temp_on = $this->_post('temp_on', '');
        $temp_l = $this->_post('temp_l', '');
        $temp_h = $this->_post('temp_h', '');
        $action = new UserDeviceAction();
        $id = intval($id);
        if ($id <= 0) {
            $this->apiReturnErr('设备id无效(-1)');
        }
        $result = $action->getInfo($id);
        $entity = $result['info'];
        if (empty($entity)) {
            $this->apiReturnErr('设备id无效(-2)');
        }
        $extra = json_decode($entity['extra'], JSON_OBJECT_AS_ARRAY);

        if (ValidateHelper::isZeroOrOne($temp_on)) {
            $extra['temp_on'] = $temp_on;
        }
        if (ValidateHelper::isZeroOrOne($ph_on)) {
            $extra['ph_on'] = $ph_on;
        }
        if (!empty($ph_l)) {
            $extra['ph_l'] = $ph_l;
        }
        if (!empty($ph_h)) {
            $extra['ph_h'] = $ph_h;
        }
        if (!empty($temp_l)) {
            $extra['temp_l'] = $temp_l;
        }
        if (!empty($temp_h)) {
            $extra['temp_h'] = $temp_h;
        }
        $data = [];
        $data['extra'] = json_encode($extra);
        $result = (new UserDeviceAction())->userDeviceChange($id, $data);
        $this->exitWhenError($result, true);
    }

    /**
     * 更新aph300设备的额外信息
     */
    public function updateAph300Extra()
    {
        $id = $this->_post('id', 0);
        $first_update_time = $this->_post('first_update_time', '');
        $last_update_time = $this->_post('last_update_time', '');
        $action = new UserDeviceAction();
        $push_cfg = $this->_post('push_cfg', '');
        $phL = $this->_post('ph_l', '');
        $phH = $this->_post('ph_h', '');
        $tempL = $this->_post('temp_l', '');
        $tempH = $this->_post('temp_h', '');

        $id = intval($id);
        if ($id <= 0) {
            $this->apiReturnErr('设备id无效(-1)');
        }
        $result = $action->getInfo($id);
        $entity = $result['info'];
        if (empty($entity)) {
            $this->apiReturnErr('设备id无效(-2)');
        }
        $extra = json_decode($entity['extra'], JSON_OBJECT_AS_ARRAY);

        if (strlen($tempL) > 0) {
            $extra['temp_l'] = $tempL;
        }
        if (strlen($tempH) > 0) {
            $extra['temp_h'] = $tempH;
        }
        if (strlen($phH) > 0) {
            $extra['ph_h'] = $phH;
        }
        if (strlen($phL) > 0) {
            $extra['ph_l'] = $phL;
        }
        if (strlen($push_cfg) > 0) {
            $extra['push_cfg'] = $push_cfg;
        }
        if (!empty($first_update_time)) {
            $extra['first_upd'] = $first_update_time;
        }

        if (!empty($last_update_time)) {
            $extra['last_upd'] = $last_update_time;
        }
        $data = [];
        $data['extra'] = json_encode($extra);
        $result = (new UserDeviceAction())->userDeviceChange($id, $data);
        $this->exitWhenError($result, true);
    }

    public function query()
    {
        $uid = $this->_post('uid', '');
        $result = (new UserDeviceAction())->query($uid);
        if (is_array($result['info'])) {
            $now = time();
            foreach ($result['info'] as &$vo) {
                $vo['is_disconnect'] = 0;
                if (empty($vo['tcp_client_id'])) {
                    $vo['is_disconnect'] = 2;
                } elseif ($vo['prev_login_time'] < $now - 3*24*3600) {
                    $vo['is_disconnect'] = 2;
                }
            }
        }
        $this->exitWhenError($result, true);
    }

    /**
     *
     * 101: 增加设备温度值上下限
     * 102: 增加工作状态通知开关
     * 103: 废弃接口
     */
    public function change()
    {
        $this->checkVersion([103], "接口已废弃");
        $id = $this->_post('id', '');
        $device_nickname = $this->_post('device_nickname', '');
        $nickname_a = $this->_post('nickname_a', '');
        $nickname_b = $this->_post('nickname_b', '');
        $temp_min = $this->_post('temp_min', '');
        $temp_max = $this->_post('temp_max', '');
        $temp_alert = $this->_post('temp_alert', '');
        $is_state_notify = $this->_post('is_state_notify', '');
        $entity = array(
            'update_time' => time()
        );
        if (!empty($device_nickname)) {
            $entity['device_nickname'] = $device_nickname;
        }
        if (!empty($nickname_a)) {
            $entity['nickname_a'] = $nickname_a;
        }
        if (!empty($nickname_b)) {
            $entity['nickname_b'] = $nickname_b;
        }
        if (!empty($temp_min)) {
            $entity['temp_min'] = $temp_min;
        }
        if (!empty($temp_max)) {
            $entity['temp_max'] = $temp_max;
        }

        if (strlen($temp_alert) > 0) {
            $entity['temp_alert'] = intval($temp_alert);
        }
        if (strlen($is_state_notify) > 0) {
            $entity['is_state_notify'] = intval($is_state_notify);
        }

        $result = (new UserDeviceAction())->UserDevicechange($id, $entity);
        $this->exitWhenError($result, true);
    }

    /**
     * 101 增加时区
     * 102 增加语言 zh-cn | en
     */
    public function add()
    {
        $this->checkVersion(["100", "102"], "102 增加语言参数lang");
        $did = $this->_post('did', '');
        $uid = $this->_post('uid', '');
        $device_nickname = $this->_post('device_nickname', '森森设备');
        $device_type = $this->_post('device_type', '');
        $timezone = $this->_post('timezone', 8);//时区
        $lang = $this->_post('lang', 'zh-cn');//语言
        $extra = $this->_post('extra', '');//设备额外信息
        // 转化为大写
        $did = strtoupper($did);

        if (empty($device_type)) {
            $device_type = DeviceTypeHelper::getDeviceType($did);
        }
        $checkResult = $this->checkLoginIp($did);

        if (!$checkResult['status']) {
            $this->apiReturnErr($checkResult['info']);
        }

        $extra = $this->setDefaultExtra($did, $extra);

        $time = time();
        $entity = array(
            'did' => $did,
            'device_nickname' => $device_nickname,
            'uid' => $uid,
            'device_type' => $device_type,
            'create_time' => $time,
            'update_time' => $time,
            'timezone' => $timezone,
            'lang' => $lang,
            'extra' => $extra,
        );

        $result = (new UserDeviceAction())->add($entity);
        $this->exitWhenError($result, true);
    }

    public function del()
    {
        $id = $this->_post('id', '');
        $result = (new UserDeviceAction())->UserDeviceDel($id);
        $this->exitWhenError($result, true);
    }

    private function setDefaultExtra($did, $extra)
    {
        if (!empty($extra)) {
            $extra = json_decode($extra, JSON_OBJECT_AS_ARRAY);
        } else {
            $extra = [];
        }

        $type = DeviceTypeHelper::getDeviceType($did);

        switch ($type) {
            case DeviceType::Did_FilterVat:

                break;
            case DeviceType::Did_AQ806:
                $extra['ph_l'] = 4 * 100;
                $extra['ph_h'] = 8 * 100;
                $extra['ph_on'] = 0;
                $extra['temp_on'] = 0;
                $extra['temp_l'] = 10 * 10;
                $extra['temp_h'] = 35 * 10;
                break;
            case DeviceType::Did_APH300:
                $extra['ph_l'] = 4 * 100;
                $extra['ph_h'] = 8 * 100;
                $extra['temp_l'] = 10 * 10;
                $extra['temp_h'] = 35 * 10;
                $extra['ph_on'] = 0;
                $extra['temp_on'] = 0;
                break;
            default:
                break;
        }

        return json_encode($extra);
    }

    private function checkLoginIp($did)
    {

        $type = DeviceTypeHelper::getDeviceType($did);

        if ($type == DeviceType::Did_FilterVat) {
            $result = (new FilterVatDeviceLogic())->getInfo(['did' => $did]);
            if (ValidateHelper::legalArrayResult($result) && $result['info']['did'] == $did) {
                $last_login_ip = $result['info']['last_login_ip'];
                $limit_country = $result['info']['limit_country'];
                if (empty($limit_country)) {
                    return ResultHelper::success('valid');
                }
                if (empty($last_login_ip)) {
                    return ResultHelper::error(lang('err_device_not_online'));
                }

                $result = $this->getCountryByIp($last_login_ip);
                if (!$result['status']) {
                    return ResultHelper::error(lang('err_retry'));
                }
                $country = $result['info'];
                if (strpos($limit_country, $country) === false) {
                    // 当前设备登录ip所在国家，不在可访问的列表中
                    $countryNames = '';
                    $list = explode(",", trim($limit_country, ","));

                    foreach ($list as $vo) {
                        if (strlen($countryNames) > 0) {
                            $countryNames .= ',';
                        }
                        $countryNames .= lang($vo);
                    }
                    return ResultHelper::error(lang('err_invalid_country', ['country' => $countryNames]));
                }
            } else {
                return ResultHelper::error(lang('err_invalid_did'));
            }
        }

        return ResultHelper::success('valid');
    }

    private function getCountryByIp($ip)
    {
        $result = IP::find($ip);
        if (count($result) > 0) {
            $country = $result[0];
            if ($country == '保留地址') {
                $country = '';
            }
        }
        if (!empty($country)) {
            return ResultHelper::success($country);
        }
        $context = stream_context_create(array(
            'http' => array(
                'timeout' => 5 //超时时间，单位为秒
            )
        ));


        // 淘宝ip接口获取
        $info = @file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip, 0, $context);
        if ($info != false) {
            $info = json_decode($info, JSON_OBJECT_AS_ARRAY);

            if ($info != false && is_array($info) && array_key_exists('code', $info)) {
                $code = intval($info['code']);
                if ($code == 0) {
                    $data = $info['data'];
                    $country = $data['country'];
                    return ResultHelper::success($country);
                }
            }
        }

        $info = @file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" . $ip, 0, $context);
        if ($info !== false) {
            $info = json_decode($info, JSON_OBJECT_AS_ARRAY);
            if ($info != false && is_array($info) && array_key_exists('ret', $info)) {
                $ret = intval($info['ret']);
                if ($ret == 1) {
                    $country = $info['country'];
                    return ResultHelper::success($country);
                }
            }
        }
        return ResultHelper::error('device login ip is invalid');
    }
}